<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 彩虹
 */
class CaihongController extends PayController{
    protected $config;

    public function pay($array){
        //$this->config = M("Channel")->where(array('id'=>$array['channel']))->find();
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>'011']);
        }

        //$product = M("Product")->where(["id"=> I("request.pay_bankcode","")])->find();
        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>'011']);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['merchantCode'] = $this->config['mch_id'];

        //echo $this->config['paytype']."<br/>";
        switch($this->config['paytype']){
            //微信
            case 1:
                $data['businessType'] = "01";
                $data['clientIp'] = $_SERVER['REMOTE_ADDR'];
                break;
            //支付宝,支付宝H5
            case 3:
            case 4:
                $data['businessType'] = "15";
                $data['clientIp'] = $_SERVER['REMOTE_ADDR'];
                break;
            //网银跳转
            case 5:
                $data['businessType'] = "14";
                break;
            //银联快捷
            case 13:
                $data['businessType'] = "13";
                break;
            default:
                $this->showmessage('不支持此产品!',['code'=>'011']);
        }

        $data['orderNo'] = $return['orderid'];
        $data['amount'] = intval($return['amount'] * 100);
        $data['desc'] = 'zf';
        $data['noticeUrl'] = $return['notifyurl'];
        $data['returnUrl'] = $return['callbackurl'];

        ksort($data);
        $str = arrToUrlStr($data)."&key=".$this->config['signkey'];
        $data['sign'] = md5($str);

        $apiurl = $this->config['gateway'];

        $json_data = json_encode($data);



        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $apiurl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false );
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: '.strlen($json_data)));
        $res = curl_exec($ch);
        curl_close($ch);

        // {"code":"0003","message":"请求Content-Type错误,请使用application/json形式请求"}
        if(!$res){
            $this->showmessage('获取数据失败!',['code'=>'011']);
        }

        //保存请求返回
        M("Order")->where([ 'pay_orderid'=>$return['orderid']])->save(["rd_return"=>$res]);
        $res = json_decode($res, true);



        /* echo '<pre>';
        echo "请求网关: ".$this->config['gateway']."<br/><br/>";
        print_r($data);
        echo "postdata: ".$json_data.'<br/><br/>';
        echo "返回数据：<br/>";
        print_r($res); echo '</pre>'; */

        // echo '<pre/>'; print_r($res);exit;
        if(!$res || empty($res)){
            $this->showmessage('获取的数据格式有误!',['code'=>'011']);
        }

        if($res['code'] != '0000'){
            $this->showmessage($res['message'],['code'=>'011']);
        }

        if(isMobile() && in_array($this->config['paytype'],[3,4])){
            header("location: {$res['tradeUrl']}"); exit;
        }

        if($this->config['paytype'] == 4){
            header("location: {$res['tradeUrl']}"); exit;
        }

        if(in_array($this->config['paytype'], [1,3,4])){
            //header("location: {$res['tradeUrl']}"); exit;
            $paytype = transArr( C("PAYTYPES"), "id");

            $this->assign("title", $paytype[$this->config['paytype']]);
            $this->assign("return", $return);
            $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?data=" .$res['tradeUrl']); //tradeUrl
            $this->display("WeiXin/Pay");
        }else{
            echo $res['html']; exit;
        }
    }

    //通知
    public function notifyurl(){
        //file_put_contents("g.txt", var_export($_REQUEST, true) . "\r\n\r\n");
        //file_put_contents("g.txt", var_export($_POST, true) . "\r\n\r\n", FILE_APPEND);
        //file_put_contents("g.txt", var_export($_GET, true) . "\r\n\r\n", FILE_APPEND);
        //file_put_contents("g.txt", file_get_contents('php://input') . "\r\n\r\n", FILE_APPEND);
        //file_put_contents("g.txt", date("Y-m-d H:i:s", time()) . "\r\n\r\n", FILE_APPEND);

        $p = file_get_contents('php://input');
        //$p = '{"code":"0000","merchantOrderNo":"201807051319137418289","message":"操作成功","platformOrderNo":"Ts13VZ180705131913","sign":"304fb07f1fdbaf169db784b0b6408e92","tradeAmount":"3000","tradeMessage":"交易成功","tradeStatus":"1","tradeTime":"2018-07-05 13:19:14"}';

        $p = json_decode($p, true);
        /*
         * Array
            (
                [code] => 0000
                [merchantOrderNo] => 201807051319137418289
                [message] => 操作成功
                [platformOrderNo] => Ts13VZ180705131913
                [sign] => 304fb07f1fdbaf169db784b0b6408e92
                [tradeAmount] => 3000
                [tradeMessage] => 交易成功
                [tradeStatus] => 1
                [tradeTime] => 2018-07-05 13:19:14
            )
         */

        if(!$p || empty($p)){
            exit("wrong");
        }

        if($p['code'] != '0000' && $p['tradeStatus']!=1){
            exit("pail_fail");
        }

        //获取订单信息
        $orderid = $p['merchantOrderNo'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "server_return"=> file_get_contents('php://input'),
            "pay_orderid_rd"=>$p['platformOrderNo']
        ));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>'Caihong'))->find();

        $sign = $p['sign'];
        unset($p['sign']);

        ksort($p);
        $str = arrToUrlStr($p)."&key=".$this->config['signkey'];
        $sign2 = md5($str);

        if($sign != $sign2){
            echo 'sign_wrong';exit;
        }

        //处理支付
        $this->EditMoney($find['pay_orderid'],"Caihong",0);

        //回调成功
        echo 'SUCCESS'; exit;
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}